#!/usr/bin/env python3
# _*_ coding:utf-8 _*_


# ******************************************************
# Author       : pandaZhangs
# First edited:     2024-05-24 11:24
# Last modified:	2024-05-24 11:26
# Email        : zhangs36@qq.com
# Filename     :	bpfhelper.py
# Description  : a simple script tool to transfer bpf.c
#                to skel.h for libpf 
# ******************************************************


import argparse
import subprocess
from pathlib import Path
suffix = ".bpf.c"
parser = argparse.ArgumentParser()
parser.add_argument("-n","--name",type=str,help="the ebpf kernel filename")
args = parser.parse_args()

fn = args.name

def compileBPF(name):
    cmd =f"clang -g -O2 -target bpf -D __TARGET_ARCH_x86_64 -I /usr/include/x86_64-linux-gnu -I . -c {name}.bpf.c -o {name}.bpf.o"
    ret = subprocess.run(cmd.split(" "),stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=20,universal_newlines=True)
    if ret.returncode==0:
        return ret.stdout,None
    return  "", ret.stderr
def compileSkel(name):
    cmd =f"bpftool gen skeleton {name}.bpf.o"
    with open(f'{name}.skel.h', 'wb') as fp:
        ret = subprocess.run(cmd.split(" "),stdout=fp,stderr=subprocess.PIPE,timeout=20)
        if ret.returncode==0:
            return None
        return   ret.stderr

def main():
    if len(fn)>0:
        p = Path(fn)
        if p.is_file() and p.name.endswith(suffix):
            n = p.name[:len(p.name)-len(suffix)]
            out,err = compileBPF(n)
            if err is not None:
                print(err)
                return
            print(f"{fn} has been compiled!")
            err = compileSkel(n)
            if err is not None:
                print(err)
                return
            print(f"{n}.skel.h has been generated!")
        else:
            print(f"{p.name} is invalid argument:[is file: {p.is_file()},suffix: {p.name.endswith(suffix)}]")
if __name__ == "__main__":
    main()
